package com.atguigu.e_reflect.constructor;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class Demo1 {
    public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        //反射第一步 : 获取类的字节码对象
        Class<Student> clazz = Student.class;

        //反射第二步 : 获取类中的成员[构造方法]
        //如何获取指定的构造方法对象呢 ? --> 根据形参类型的字节码对象来区分不同构造方法
        //无参构造的对象获取
        Constructor<Student> constructor1 = clazz.getDeclaredConstructor();
        //创建对象
        //Student stu1 = new Student();
        Student stu1 = constructor1.newInstance();
        System.out.println("stu1 = " + stu1);
        System.out.println("--------------------------------------------");

        //有参构造的对象获取 -> String name
        Constructor<Student> constructor2 = clazz.getDeclaredConstructor(String.class);
        Student stu2 = constructor2.newInstance("张三");
        System.out.println("stu2 = " + stu2);
        System.out.println("--------------------------------------------");

        //有参构造的对象获取 -> int age
        Constructor<Student> constructor3 = clazz.getDeclaredConstructor(int.class);
        Student stu3 = constructor3.newInstance(20);
        System.out.println("stu3 = " + stu3);
        System.out.println("--------------------------------------------");

        //有参构造的对象获取 -> String name , int age
        Constructor<Student> constructor4 = clazz.getDeclaredConstructor(String.class, int.class);

        //因为没有权限 所以 开启暴力反射开关
        constructor4.setAccessible(true);

        Student stu4 = constructor4.newInstance("李四", 18);
        System.out.println("stu4 = " + stu4);

        System.out.println("--------------------------------------------");
        //使用字节码对象快速获取类的对象
        Student stu5 = clazz.newInstance();
        System.out.println("stu5 = " + stu5);

    }
}
